/* a server in the unix domain */
#include <sys/socket.h>
#include <sys/un.h>
#include <iostream>
#include "../MessageAsset/Message.h"

#define SERVER_ADDRESS "/Users/macos2/Desktop/server_socket"
#define CLIENT_ADDRESS "/Users/macos2/Desktop/client_socket"

void error(const char *);

int main(int argc, char *argv[])
{
   int sockfd, n;
   socklen_t socklen;
   struct sockaddr_un client_address, server_address;
   
   bzero(&server_address, sizeof(server_address));
   server_address.sun_family = AF_UNIX;
   strcpy(server_address.sun_path, SERVER_ADDRESS);

   if ((sockfd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) error("creating socket");
   socklen = sizeof(struct sockaddr_un);
   unlink(SERVER_ADDRESS);
   if(bind(sockfd, (struct sockaddr*) &server_address, socklen) < 0) error("binding socket");
   do
   {
       char receive_buffer[1024] = {0};

       n = recvfrom(sockfd, receive_buffer, 1024, 0, (struct sockaddr*) &client_address, &socklen);
       if (n < 0) error("recvfrom");
       printf("received %d bytes\n", n);

       Message* msg = (Message*) receive_buffer;

       printf("Received a datagram:\n");
       printf("char val: %c\n", msg->char_val);
       printf("int_val: %d\n", msg->int_val);
       printf("float val: %f\n", msg->float_val);
       printf("double val: %f\n", msg->double_val);
       printf("content val: %s\n", msg->content);

       n = sendto(sockfd, "Got your message\n", 17, 0, (struct sockaddr*) &client_address, socklen);
       if (n < 0) error("sendto");
       printf("sent %d bytes\n", n);
//       break;
   } while (n > 0);

   close(sockfd);
   return 0;
}

void error(const char *msg)
{
    perror(msg);
    exit(0);
}
